package top.yqingyu.trans$client.main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author YYJ
 * @version 1.0.0
 * @date 2022/4/23 19:38
 * @description
 * @modified by
 */
public class HeartBeatThread implements Runnable {

    final static Logger logger = LoggerFactory.getLogger(HeartBeatThread.class);
    private ScheduledExecutorService service;

    private final TransClient client;

    private HeartBeatThread(TransClient client) {
        this.client = client;
    }

    public static void init(TransClient client) {
        HeartBeatThread th = new HeartBeatThread(client);
        th.service = Executors
                .newSingleThreadScheduledExecutor();
        th.service.scheduleAtFixedRate(th, 5, client.clientConf.HEART_BEAT_TIME, TimeUnit.MILLISECONDS);
    }

    public void shutdown() {
        service.shutdown();
    }

    @Override
    public void run() {
        if (client.running.get()) {
            client.REQ_MSG_QUEUE.add(client.clientConf.HEART_BEAT_MSG);
        } else {
            service.shutdown();
            logger.warn("shutdown");
        }
        ;
    }
}
